/**************************
 * Project: ePoverty
 * Filename: SortableTable.java
 * Description: Sortable, resizable, and tooltip-enabled table.
 * Name: Bunna Veth
 * Date: Apr 13, 2012
 **************************/
package epoverty;

import java.awt.Point;
import java.awt.event.MouseEvent;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class SortableTable extends JTable
{
    //Fields
    String[] headerToolTips;

    //Constructor
    public SortableTable(ObjectTableModel model)
    {
        setModel(model);
        setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        setRowSorter(new TableRowSorter<TableModel>(model));
        headerToolTips = new String[getColumnCount()];
    }

    //Resize columns (non-positive widths will be left alone)
    public void setColumnWidths(int... widths)
    {
        for (int i = 0; i < widths.length; i++)
        {
            TableColumn column = getColumnModel().getColumn(i);
            if(widths[i] > 0)
                column.setPreferredWidth(widths[i]);
        }
    }

    //Sets the header tooltips
    public void setHeaderToolTips(String[] tooltips)
    {
        headerToolTips = tooltips;
    }

    //Allows header tooltip text to display
    @Override
    protected JTableHeader createDefaultTableHeader()
    {
        return new JTableHeader(columnModel)
        {
            @Override
            public String getToolTipText(MouseEvent event)
            {
                Point point = event.getPoint();
                int index = columnModel.getColumnIndexAtX(point.x);
                int realIndex = columnModel.getColumn(index).getModelIndex();
                return headerToolTips[realIndex];
            }
        };
    }
}//end class